package org.mycollections;

import java.util.Comparator;

/**
 * Created by Oleksandr_Terekh on 8/19/2014.
 */
public class MyCollections {

    private static final String BS_ARR_NOT_SORTED_EX = "Array have to be sorted!";

    private MyCollections() {
    }

    /**
     * @param list
     */
    public static void sort(MyList list) {

        Object[] arr = list.toArray();

        if (list instanceof RandomAccess) {
            MyCollectionUtils.quickSort(arr, 0, arr.length - 1, null);
        } else {
            MyCollectionUtils.bubbleSort(arr, null);
        }

        list.clear();
        list.addAll(arr);
    }

    /**
     * @param list
     * @param c
     */
    public static void sort(MyList list, Comparator c) {

        Object[] arr = list.toArray();

        if (list instanceof RandomAccess) {
            MyCollectionUtils.quickSort(arr, 0, arr.length - 1, c);
        } else {
            MyCollectionUtils.bubbleSort(arr, c);
        }

        list.clear();
        list.addAll(arr);
    }

    /**
     * @param list
     * @param i
     * @param j
     */
    public static void swap(MyList list, int i, int j) {

        Object temp = list.get(i);
        list.set(i, list.get(j));
        list.set(j, temp);
    }

    /**
     * @param dest
     * @param src
     */
    public static void copy(MyList dest, MyList src) {

        dest.addAll(src.toArray());
    }

    /**
     * @param list
     */
    public static void reverse(MyList list) {

        final int size = list.size();
        final int mid = size / 2;

        if (list instanceof RandomAccess) {
            for (int i = 0; i < mid; i++) {
                swap(list, i, size - i - 1);
            }
        } else {

            for (int i = 0; i < mid; i++) {
                swap(list, i, size - i - 1);
            }
        }
    }

    /**
     * @param list
     * @param key
     * @return
     */
    public static int binarySearch(RandomAccess list, Object key) {

        int mid = -1;
        MyList list0 = (MyList) list;
        Object[] arr = list0.toArray();

        if (!MyCollectionUtils.isSorted(arr)) {
            throw new IllegalArgumentException(BS_ARR_NOT_SORTED_EX);
        }

        int lo = 0;
        int hi = arr.length - 1;
        while (lo <= hi) {
            mid = lo + (hi - lo) / 2;
            int compareResult = ((Comparable) key).compareTo(arr[mid]);
            if (compareResult < 0) {
                hi = mid - 1;
            } else if (compareResult > 0) {
                lo = mid + 1;
            } else {
                return mid;
            }
        }

        return -mid - 1;
    }

}
